<template>
	<view class="setInterval">
		<custom-bar custonName="定时设置" headColorChild="#f1f1f1"></custom-bar>
		<scroll-view class="scroll-content" scroll-y="true">
			<!-- 配置组循环 -->
			<view class="task-component" v-for="(task,i) in taskGroup" :key="i">
				<!-- 配置组头部 -->
				<view class="task-component-head">
					<view style="line-height:60rpx;margin-right:20rpx">
						<image src="@/static/icons/setteam.svg" mode="" class="set-icon">
						</image>
						{{task.name}}
					</view>
					<!-- <up-icon name="edit-pen" @click="handleEditName(task)"></up-icon> -->
					<up-modal :show="showEdit" :showConfirmButton="true" :showCancelButton="true"
						:closeOnClickOverlay="true" :buttonReverse="true" @close="showEdit = false"
						@cancel="showEdit = false" @confirm="confirmEdit" confirmColor="#25afe5">
						<view class="slot-content">
							<view class="">
								<view class="" style="width:100%;text-align:center;font-size:24rpx;margin-bottom:20rpx">
									修改配置组名称
								</view>
								<view class="edit-device-name-input">
									<up-input v-model="editName" type="text" border="surround" />
									<view class="edit-device-name-input-error" v-show="editName == ''">
										配置组名称不能为空
									</view>
								</view>
							</view>
						</view>
					</up-modal>
					<view @click="handlerUse(task)" style="margin-right:20rpx">
						<!-- <up-switch size="15" v-model="task.disable" active-color="#5effff" inactive-color="#909399" /> -->
						<view class="group-status" style="background:#d7d7d7" v-if="task.disable == 'true'">
							<up-icon name="close-circle" color="#78a489" size="30rpx"></up-icon>
							<text style="padding-left:5rpx">已禁用</text>
						</view>
						<view class="group-status" style="background:#d7fde8" v-else>
							<image src="@/static/icons/close78a489.png" mode=""
								style="width:30rpx;height:30rpx;padding-right:5rpx">
							</image>
							<text>已启用</text>
						</view>
					</view>
					<up-icon name="trash-fill" color="red" @click="delGroup(i)"></up-icon>
				</view>
				<!-- 选择星期 -->
				<view class="week-list">
					<view class="" v-for="(item,index) in weekData" :key="index">
						<view class="" @click="handlerClickDay(item,index,i)"
							:class="getDayClass(item.id, task.remarks, i)">
							{{item.day}}
						</view>
					</view>
					<!-- <up-checkbox-group v-model="task.remarks" @change="(val) => handlerClickWeek(val, i)">
						<view v-for="(item,index) in weekData">
							<up-checkbox :key="item.id" :name="item.id" :label="item.day"
								:disabled="item.disabled && item.cIndex!=i">
								{{item.day}}
							</up-checkbox>
						</view>
					</up-checkbox-group> -->
				</view>
				<!-- 时间段配置 -->

				<view class="time-set-title">
					<view class="">
						时间段配置({{task.scheList.length}}/12)
					</view>
					<view class="" style="width:120rpx">
						<up-button type="primary" text="添加" icon="plus" size="mini" @click="handlerAdd(i)"></up-button>
					</view>
				</view>
				<view class="set-part">
					<view class="set-part-data" style="padding:10rpx">
						<image src="@/static/icons/clock0b0b0b.png" mode=""
							style="width:32rpx;height:32rpx;padding-right:5rpx"></image>
						<text>时间</text>
					</view>
					<!-- <view class="set-part-data" style="padding:10rpx">
						<image src="@/static/icons/close0b0b0b.png" mode=""
							style="width:28rpx;height:28rpx;padding-right:5rpx"></image>
						<text>开关机</text>

					</view> -->
					<view class="set-part-data set-part-data-temp">
						<image src="@/static/icons/temp0b0b0b.png" mode="" style="width:30rpx;height:30rpx;">
						</image>
						<text>温度(℃)</text>
					</view>
					<!-- 	<view class="set-part-data" style="padding:10rpx">
						<image src="@/static/icons/wind0b0b0b.png" mode=""
							style="width:30rpx;height:30rpx;padding-right:5rpx"></image>
						<text>风速</text>
					</view> -->
					<view class="set-part-del" style="display:flex;align-items:center;visibility:hidden;">
						<up-icon name="trash-fill" color="red" @click="handlerDel(i,index)"></up-icon>
					</view>
				</view>
				<view v-for="(time,index) in task.scheList" :key="index">
					<!-- 配置组中的每个配置项 -->

					<view>
						<view class="set-part-item">
							<!-- 时间 -->
							<view class="set-part-data"
								style="border:1px solid #f5f5f5;border-radius:10px;background:#fff;padding:10rpx">
								<view class="" @click="handlerPicker('time',time)">
									<view class="custom-input">
										{{time.showTime}}
										<up-icon name="arrow-down" color="#909399"></up-icon>
									</view>
									<up-datetime-picker ref="datetimePickerRef" :show="time.showTimePicker"
										v-model="time.showTime" @confirm="(e) => handleTimeConfirm(e, i, index)"
										@cancel="time.showTimePicker = false" mode="time"></up-datetime-picker>
								</view>
							</view>
							<!-- 温度 -->
							<view class="set-part-data"
								style="border:1px solid #f5f5f5;border-radius:10px;background:#fff;padding:10rpx">
								<view class="" @click="handlerPicker('temp',time)">
									<view class="custom-input">
										{{time.tempset}}℃
										<up-icon name="arrow-down" color="#909399" style="padding-left:10rpx"></up-icon>
									</view>
									<up-picker :show="time.showTempPicker" :modelValue="[time.tempset]"
										@confirm="(e) => handleTempConfirm(e, i, index)"
										@cancel="time.showTempPicker = false" :columns="tempSelectOptions"></up-picker>
								</view>
							</view>
							<view class="set-part-del" style="display:flex;align-items:center">
								<up-icon name="trash-fill" color="red" @click="handlerDel(i,index)"></up-icon>
							</view>

						</view>
					</view>

				</view>

			</view>
		</scroll-view>
		<view class="set-btn">
			<view class="set-btn-add" @click="handlerAddGroup">
				<up-icon name="plus" bold></up-icon><text style="margin-left:15rpx">添加配置组</text>
			</view>
			<view class="set-btn-edit">
				<view class="set-btn-edit-item">
					<up-button type="primary" size="small" @click="handlerSubmit">保存</up-button>
				</view>
				<view class="set-btn-edit-item">
					<up-button type="primary" :plain="true" size="small" @click="handlerCancel">取消</up-button>
				</view>

			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive
	} from "vue"
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	const closeOption = ref([]);
	const taskGroup = reactive([])
	const deviceId = ref(null)
	const dataId = ref(null)
	const deviceInfo = ref(null)
	const showEdit = ref(false);
	const editName = ref('');
	const currentTask = ref(null);
	const tempSelectedDays = ref({});
	const deviceName = ref('')
	const identity = ref(null)
	//cIndex为第几个配置组选中
	const weekData = ref([{
			day: "周日",
			id: "64",
			disabled: false,
			cIndex: null
		},
		{
			day: "周一",
			id: "1",
			disabled: false,
			cIndex: null
		},
		{
			day: "周二",
			id: "2",
			disabled: false,
			cIndex: null
		},
		{
			day: "周三",
			id: "4",
			disabled: false,
			cIndex: null
		},
		{
			day: "周四",
			id: "8",
			disabled: false,
			cIndex: null
		},
		{
			day: "周五",
			id: "16",
			disabled: false,
			cIndex: null
		},
		{
			day: "周六",
			id: "32",
			disabled: false,
			cIndex: null
		},

	])
	const tempSelectOptions = reactive([])

	onLoad((options) => {
		let id = decodeURIComponent(options.id);
		if (id) {
			dataId.value = id;
			deviceId.value = decodeURIComponent(options.equipNo)
			deviceName.value = decodeURIComponent(options.devName)
			getDevInfo()
			getData()
		}
		//初始化选项
		closeOption.value = [getDict('sys_switch_status')];

		identity.value = uni.getStorageSync("identity")

	});

	const controlClick = () => {
		if (identity.value == false) {
			// 0  解锁  1 锁后台  2 开放开关机 3 全锁
			if (deviceInfo.value.devKeyLock == 3 || deviceInfo.value.devKeyLock == 2) {
				uni.showToast({
					title: '设备已锁定,无法操作',
					icon: 'none'
				})
				return false;
			}
		}
		return true;
	}

	const getDict = (type) => {
		let arr = uni.getStorageSync(type) || [];
		return arr;
	}

	const getLabel = (type, value) => {
		let arr = uni.getStorageSync(type) || [];
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].dictValue == value) {
				return arr[i].dictLabel;
			}
		}
		return '';
	}

	const handlerAddGroup = () => {
		if (!controlClick()) return;
		// 如果taskGroup为空，直接添加
		if (taskGroup.length === 0) {
			let init = {
				"remark": "[]",
				"remarks": [],
				"id": null,
				"name": getNewGroupName(),
				"disable": 'false',
				"scheList": []
			}
			taskGroup.push(init);
			return;
		}
		// 检查现有配置组是否都有选择日期
		const hasEmptyRemark = taskGroup.some(task => {
			// 检查正式选中的日期和临时选中的日期
			const hasRemarks = task.remarks && task.remarks.length
			const hasTempSelected = tempSelectedDays.value[taskGroup.indexOf(task)] &&
				tempSelectedDays.value[taskGroup.indexOf(task)].length > 0;
			return !hasRemarks && !hasTempSelected;
		});

		if (hasEmptyRemark) {
			uni.showToast({
				title: '请先为现有配置组选择日期',
				icon: "none"
			});
			return;
		}
		// 检查是否所有星期都已被占用
		const allWeekDays = ['1', '2', '4', '8', '16', '32', '64']; // 周一到周日的ID
		const selectedDays = new Set();

		// 收集所有已被选中的星期（包括remarks和临时选中的）
		taskGroup.forEach((task, index) => {
			// 添加正式选中的日期
			if (task.remarks && Array.isArray(task.remarks)) {
				task.remarks.forEach(remark => selectedDays.add(remark.toString()));
			}

			// 添加临时选中的日期
			if (tempSelectedDays.value[index] && Array.isArray(tempSelectedDays.value[index])) {
				tempSelectedDays.value[index].forEach(day => selectedDays.add(day));
			}
		});

		// 检查是否所有星期都已被选中
		const allSelected = allWeekDays.every(day => selectedDays.has(day));

		if (allSelected) {
			uni.showToast({
				title: '所有星期都已被配置，无法添加新的配置组',
				icon: "none"
			});
			return;
		}
		// 限制配置组最多20个
		if (taskGroup.length >= 20) {
			uni.showToast({
				title: '最多只能添加20个配置组',
				icon: "none"
			});
			return;
		}
		let init = {
			"remark": "[]",
			"remarks": [],
			"id": null,
			"name": getNewGroupName(),
			"disable": 'false',
			"scheList": []
		}
		taskGroup.push(init);

	}
	const getNewGroupName = () => {
		// 提取当前所有配置组的序号（支持一到二十的中文数字）
		const usedNumbers = taskGroup.map(item => {
			// 修改正则表达式以支持复合中文数字
			const match = item.name.match(/配置组([一二三四五六七八九十]+)(?![一二三四五六七八九十])/);
			if (match) {
				// 将中文数字转换为阿拉伯数字
				const chineseToNumber = {
					'一': 1,
					'二': 2,
					'三': 3,
					'四': 4,
					'五': 5,
					'六': 6,
					'七': 7,
					'八': 8,
					'九': 9,
					'十': 10,
					'十一': 11,
					'十二': 12,
					'十三': 13,
					'十四': 14,
					'十五': 15,
					'十六': 16,
					'十七': 17,
					'十八': 18,
					'十九': 19,
					'二十': 20
				};
				return chineseToNumber[match[1]] || 0;
			}
			return 0;
		}).filter(num => num > 0).sort((a, b) => a - b);

		// 如果没有已使用的序号，直接返回"一"
		if (usedNumbers.length === 0) {
			return `配置组一`;
		}

		// 查找第一个缺失的序号
		let newNameNumber = 1;
		for (let i = 0; i < usedNumbers.length; i++) {
			if (usedNumbers[i] === newNameNumber) {
				newNameNumber++;
			} else if (usedNumbers[i] > newNameNumber) {
				// 找到了缺失的序号
				break;
			}
		}

		// 限制最多20个配置组
		if (newNameNumber > 20) {
			newNameNumber = 20;
		}

		// 将阿拉伯数字转换为中文大写
		const numberToChinese = (num) => {
			const chineseNumbers = {
				1: '一',
				2: '二',
				3: '三',
				4: '四',
				5: '五',
				6: '六',
				7: '七',
				8: '八',
				9: '九',
				10: '十',
				11: '十一',
				12: '十二',
				13: '十三',
				14: '十四',
				15: '十五',
				16: '十六',
				17: '十七',
				18: '十八',
				19: '十九',
				20: '二十'
			};
			return chineseNumbers[num] || '一';
		};

		return `配置组${numberToChinese(newNameNumber)}`;
	};
	const handlerAdd = (taskIndex) => {
		if (!controlClick()) return;
		if (taskGroup[taskIndex].scheList.length < 12) {
			let init = {
				"id": null,
				"day": null,
				"time": "0", // 时间换算成一天内的分钟数的数值
				"onOff": "1", // 开机1；关机0
				// "fan": null, //风速根据字典取值
				"tempset": null, //目标温度
				"groupId": null,
				"showClosePicker": false,
				"showTempPicker": false,
				"showTimePicker": false,
				"showTime": "00:00",
				"showFanPicker": false,
				"disable": "true"
			}
			taskGroup[taskIndex].scheList.push(init);
		} else {
			uni.showToast({
				title: '最多只能添加12个时间段',
				icon: 'error'
			})
		}

	}

	const delGroup = (taskIndex) => {
		if (!controlClick()) return;
		uni.showModal({
			title: '温馨提示',
			content: '确定要删除该配置组吗？',
			success: res => {
				if (res.confirm) {
					taskGroup.splice(taskIndex, 1);
				}
			}
		})
	}

	const handlerDel = (taskIndex, timeIndex) => {
		if (!controlClick()) return;
		uni.showModal({
			title: '温馨提示',
			content: '确定要删除该时间段吗？',
			success: res => {
				if (res.confirm) {
					taskGroup[taskIndex].scheList.splice(timeIndex, 1);
				}
			}
		})
	}
	// 修改配置组名称
	const handleEditName = (task) => {
		currentTask.value = task;
		editName.value = task.name; // 初始化输入框内容
		showEdit.value = true;
	}

	const confirmEdit = () => {
		if (!controlClick()) return;
		if (currentTask.value) {
			currentTask.value.name = editName.value || '未命名';
		}
		showEdit.value = false;
	};
	const handlerUse = (task) => {
		if (!controlClick()) return;
		if (task.disable == 'false') {
			task.disable = 'true'
		} else {
			task.disable = 'false'
		}
	}

	const handlerPicker = (val, time) => {
		if (!controlClick()) return;
		if (val == 'time') {
			time.showTimePicker = true
		}
		if (val == 'temp') {
			time.showTempPicker = true
		}
	}

	//时间转为分钟
	const timeToMinutes = (timeStr) => {
		const [hours, minutes] = timeStr.split(':').map(Number);
		return hours * 60 + minutes;
	};

	// 分钟换为时间
	const minutesToTime = (totalMinutes) => {
		if (!totalMinutes) {
			return '00:00'
		}
		const hours = Math.floor(totalMinutes / 60);
		const minutes = totalMinutes % 60;
		// 补零处理确保两位数格式
		return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
	};
	const handlerClickWeek = (data, groupIndex) => {
		const checks = new Set();
		// 遍历所有配置组的选中项
		for (const task of taskGroup) {
			for (const remark of task.remarks || []) {
				checks.add(remark);
			}
		}
		for (var i = 0; i < weekData.value.length; i++) {
			if (checks.has(weekData.value[i].id)) {
				weekData.value[i].disabled = true;
				if (weekData.value[i].cIndex == null) {
					weekData.value[i].cIndex = groupIndex
				}
			} else {
				weekData.value[i].cIndex = null;
				weekData.value[i].disabled = false;
			}

		}
	}

	const handlerClickDay = (data, index, groupIndex) => {
		if (!controlClick()) return;
		// 检查是否被禁用
		const disabledDays = getDisabledDays(groupIndex);
		if (disabledDays.has(data.id.toString())) {
			// 如果日期已被禁用，不执行任何操作
			return;
		}
		// 统一使用数字类型进行比较
		const dayIdNum = parseInt(data.id);

		// 检查该日期当前是否是选中状态 (dayTrue)
		const isCurrentlySelected = taskGroup[groupIndex].remarks &&
			taskGroup[groupIndex].remarks.includes(dayIdNum);

		if (isCurrentlySelected) {
			// 如果当前是选中状态，点击后变为未选中状态
			// 从 remarks 数组中移除该日期
			taskGroup[groupIndex].remarks = taskGroup[groupIndex].remarks.filter(
				remark => remark != dayIdNum
			);
			if (tempSelectedDays.value[groupIndex]) {
				taskGroup[groupIndex].remark = [
					...taskGroup[groupIndex].remarks,
					...tempSelectedDays.value[groupIndex]
				]
			} else {
				taskGroup[groupIndex].remark = [...taskGroup[groupIndex].remarks]
			}
		} else {
			// 如果当前是未选中状态，则添加到临时选中
			if (!tempSelectedDays.value[groupIndex]) {
				tempSelectedDays.value[groupIndex] = [];
			}

			const dayId = data.id.toString();
			const tempDays = tempSelectedDays.value[groupIndex];
			const selectedIndex = tempDays.indexOf(dayId);

			if (selectedIndex > -1) {
				// 如果已临时选中，则取消选中
				tempDays.splice(selectedIndex, 1);
			} else {
				// 如果未选中，则添加选中
				tempDays.push(dayId);

			}
			taskGroup[groupIndex].remark = [...taskGroup[groupIndex].remarks, ...(tempSelectedDays.value[
				groupIndex] || [])]
		}
	}

	// 获取已被其他配置组选中的日期
	const getDisabledDays = (currentGroupIndex) => {
		const disabledDays = new Set();

		// 遍历所有配置组，收集已被选中的日期
		taskGroup.forEach((task, index) => {
			if (index !== currentGroupIndex && task.remarks) {
				task.remarks.forEach(remark => {
					disabledDays.add(remark.toString());
				});
			}
		});
		// 也要考虑临时选中的日期
		Object.keys(tempSelectedDays.value).forEach(groupIndex => {
			if (parseInt(groupIndex) !== currentGroupIndex && tempSelectedDays.value[groupIndex]) {
				tempSelectedDays.value[groupIndex].forEach(dayId => {
					disabledDays.add(dayId);
				});
			}
		});

		return disabledDays;
	};
	// 获取星期的class名
	const getDayClass = (dayId, remarks, groupIndex) => {
		let classes = '';

		// 检查是否在 remarks 中（包括接口返回的原始选中状态）
		const isOriginallySelected = remarks &&
			(remarks.includes(dayId.toString()) || remarks.includes(parseInt(dayId)));

		if (isOriginallySelected) {
			// 如果在 remarks 中，则为 dayTrue
			classes += 'dayTrue ';
		} else {
			// 如果不在 remarks 中，则为 dayFalse
			classes += 'dayFalse ';
		}

		// 添加临时选中状态（只有 dayFalse 才能有 daySelect 状态）
		if (tempSelectedDays.value[groupIndex] &&
			tempSelectedDays.value[groupIndex].includes(dayId.toString())) {
			// 只有 dayFalse 才能有 daySelect 状态
			if (!isOriginallySelected) {
				classes += 'daySelect';
			}
		}


		// 检查是否被禁用
		const disabledDays = getDisabledDays(groupIndex);
		if (disabledDays.has(dayId.toString())) {
			classes += ' dayDisabled';
		}

		return classes.trim();
	};
	//开关回调
	const handleOnOffConfirm = (e, taskIndex, timeIndex) => {
		if (taskGroup[taskIndex] && taskGroup[taskIndex].scheList[timeIndex]) {
			taskGroup[taskIndex].scheList[timeIndex].onOff = e.value[0].dictValue;
			taskGroup[taskIndex].scheList[timeIndex].showClosePicker = false;
			// if (e.value[0].dictValue == '0') {
			// 	taskGroup[taskIndex].scheList[timeIndex].fan = null
			// 	taskGroup[taskIndex].scheList[timeIndex].tempset = null
			// }
		}
	}
	//时间回调
	const handleTimeConfirm = (e, taskIndex, timeIndex) => {
		if (taskGroup[taskIndex] && taskGroup[taskIndex].scheList[timeIndex]) {
			taskGroup[taskIndex].scheList[timeIndex].showTime = e.value;
			taskGroup[taskIndex].scheList[timeIndex].showTimePicker = false;
		}
	}
	//温度回调
	const handleTempConfirm = (e, taskIndex, timeIndex) => {
		if (taskGroup[taskIndex] && taskGroup[taskIndex].scheList[timeIndex]) {
			taskGroup[taskIndex].scheList[timeIndex].tempset = e.value[0];
			taskGroup[taskIndex].scheList[timeIndex].showTempPicker = false;
		}
	}
	//风速回调
	const handleFanConfirm = (e, taskIndex, timeIndex) => {
		if (taskGroup[taskIndex] && taskGroup[taskIndex].scheList[timeIndex]) {
			taskGroup[taskIndex].scheList[timeIndex].fan = e.value[0].dictValue;
			taskGroup[taskIndex].scheList[timeIndex].showFanPicker = false;
		}
	}

	const handlerGroup = () => {
		showEdit.value = true
	}


	const getData = () => {
		let data = {
			equipNo: deviceId.value,
			id: dataId.value
		}
		uni.$u.http.post('/wechat/schemeDataGet', data).then(res => {
			//处理回显数据
			taskGroup.length = 0
			if (res.dnSchemeGroupList.length) {
				res.dnSchemeGroupList.forEach(item => {
					item.remarks = JSON.parse(item.remark)
					if (item.scheList && item.scheList.length) {
						//为配置组添加独立的触发控件
						item.scheList.forEach(timeItem => {
							timeItem.showClosePicker = false;
							timeItem.showTempPicker = false;
							timeItem.showTimePicker = false;
							timeItem.showTime = minutesToTime(timeItem.time);
							timeItem.showFanPicker = false;
						})
					}
					taskGroup.push(reactive(item))
				})
			}

		})
	}
	const getDevInfo = () => {
		let data = {
			id: dataId.value
		}
		uni.$u.http.post('/wechat/getDevInfo', data).then(res => {
			if (res.success) {
				deviceInfo.value = res.data;
				// let fanArr = getDict(`sys_fan_speed_${res.data.devType}`);
				// windSelectOptions.push(fanArr);

				//温度返回了就按返的来
				let cool = res.data.tempSetBot || 5
				let hot = res.data.tempSetTop || 50
				let tempArr = [];
				for (var i = cool; i <= hot; i++) {
					tempArr.push(i + '');
				}
				tempSelectOptions.push(tempArr);
			}
		})
	}

	const handlerSubmit = () => {
		if (!controlClick()) return;
		//整理提交数据
		let result = [];

		for (var i = 0; i < taskGroup.length; i++) {
			let selectedDays = [];
			// 检查配置组内时间段是否有重复
			const timeSet = new Set();
			const duplicateTimes = [];
			for (var j = 0; j < taskGroup[i].scheList.length; j++) {
				const timeValue = taskGroup[i].scheList[j].showTime;
				if (timeSet.has(timeValue)) {
					duplicateTimes.push(timeValue);
				} else {
					timeSet.add(timeValue);
				}

				// 检查温度是否为空
				if (taskGroup[i].scheList[j].tempset === null ||
					taskGroup[i].scheList[j].tempset === undefined ||
					taskGroup[i].scheList[j].tempset === '') {
					uni.showToast({
						title: `"${taskGroup[i].name}"中存在温度未设置的时间段`,
						icon: "none"
					});
					return;
				}
			}

			// 如果有重复时间段，提示用户
			if (duplicateTimes.length > 0) {
				uni.showToast({
					title: `配置组"${taskGroup[i].name}"中存在重复时间段: ${duplicateTimes.join(', ')}`,
					icon: "none"
				});
				return;
			}
			// 处理 remark 字段，确保它是一个字符串数组
			if (Array.isArray(taskGroup[i].remark)) {
				// 如果已经是数组，直接使用
				selectedDays = taskGroup[i].remark.map(item => String(item));
			} else if (typeof taskGroup[i].remark === 'string') {
				try {
					// 如果是字符串，尝试解析为数组
					let parsedRemark = JSON.parse(taskGroup[i].remark);
					if (Array.isArray(parsedRemark)) {
						selectedDays = parsedRemark.map(item => String(item));
					} else {
						selectedDays = [String(parsedRemark)];
					}
				} catch (e) {
					// 如果解析失败，直接使用原字符串
					selectedDays = [taskGroup[i].remark];
				}
			} else {
				// 其他情况，转换为字符串
				selectedDays = [String(taskGroup[i].remark)];
			}
			if (!selectedDays.length) {
				uni.showToast({
					title: '请为所有配置组选择日期',
					icon: "none"
				});
				return;
			}
			let data = {
				name: taskGroup[i].name,
				disabled: JSON.parse(taskGroup[i].disable),
				selectedDays: selectedDays,
				timeSlots: []
			}
			let ddd = 0;
			for (var k = 0; k < selectedDays.length; k++) {
				ddd += parseInt(selectedDays[k]);
			}
			//处理时间段
			for (var j = 0; j < taskGroup[i].scheList.length; j++) {
				let init = {
					Time: timeToMinutes(taskGroup[i].scheList[j].showTime),
					OnOff: null,
					Fan: null,
					Tempset: Number(taskGroup[i].scheList[j].tempset) || null,
					//特殊 上级数组相加
					Day: ddd
				}
				data.timeSlots.push(init);
			}
			result.push(data);
		}
		const openid = uni.getStorageSync('openid') || 'owcFGvn55hwOIXTPx6qILBs-zJH4';
		let param = {
			id: deviceInfo.value.id,
			equipNo: deviceInfo.value.equipNo,
			openid: openid,
			currentSubmitData: result
		}
		uni.$u.http.post('/wechat/schemeDataSend', param).then(res => {
			if (res.success) {
				uni.showToast({
					title: '操作成功',
					icon: 'success'
				})
				//返回上一页
				uni.navigateBack()
				// uni.navigateTo({
				// 	url: `/Device/setDevide/setDevide?id=${encodeURIComponent(deviceInfo.value.id)}&&devName=${deviceName.value}`
				// })
			} else {
				uni.showToast({
					title: res.message,
					icon: 'error'
				})
			}
		})
	}

	const handlerCancel = () => {
		uni.navigateBack()
		// if (!controlClick()) return;
		// getData()
		// // 重置临时选中的日期状态
		// tempSelectedDays.value = {}
		// // 重置所有星期数据的禁用状态和索引
		// weekData.value.forEach(item => {
		// 	item.disabled = false
		// 	item.cIndex = null
		// })
	}
</script>

<style lang="scss" scoped>
	.setInterval {
		height: 100vh;
		background: #f1f1f1;
		padding: 0 30rpx;
		display: flex;
		flex-direction: column
	}

	.scroll-content {
		flex: 1;
		padding-bottom: 180rpx;
		overflow-y: auto;
	}

	.task-component {
		padding-bottom: 20rpx;
	}

	.task-component-head {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		margin-top: 20rpx;

		.set-icon {
			width: 35rpx;
			height: 35rpx;
			vertical-align: middle;
			padding-right: 10rpx;
			font-size: 40rpx;
		}

		.group-status {
			display: flex;
			color: #78a489;
			padding: 5rpx 20rpx;
			border-radius: 10px;
			font-size: 24rpx;
		}

	}

	.week-list {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		margin: 10rpx 0;

		.week-item {
			border: 1px solid #3d9dcd;
			background: #fff;
			border-radius: 5px;
			padding: 2rpx 10rpx;
		}

		.week-item-selected {
			border: 1px solid #3d9dcd;
			background: #3d9dcd;
			color: #fff;
			border-radius: 5px;
			padding: 2rpx 10rpx;
		}
	}


	.time-set-title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin: 20rpx 0 0 0;
		height: 80rpx;
	}


	.set-part {
		display: flex;
		justify-content: space-between;
		padding: 0 15rpx;
	}

	.set-part-data {
		width: 30%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 10rpx 0 0 0;
		padding: 5rpx;
	}

	.set-part-data.set-part-data-temp {
		width: 180rpx;
	}

	.set-part-item {
		display: flex;
		justify-content: space-between;
		border-bottom: 1px solid #f1f1f1;
		padding: 0 15rpx;
	}

	.set-part-item:last-child {
		border: 0;
	}

	// 底部按钮
	.set-btn {
		width: 100%;
		flex-shrink: 0;
		height: 160rpx;
		background: #fff;
		position: absolute;
		left: 0;
		bottom: 0;

		.set-btn-add {
			height: inherit;
			display: flex;
			height: 80rpx;
			justify-content: center;
			align-items: center;
		}

		.set-btn-edit {
			display: flex;
			justify-content: center;
			height: 80rpx;

			.set-btn-edit-item {
				width: 150rpx;
				line-height: 80rpx;
				margin: 15rpx 20rpx 0 20rpx;
			}
		}
	}

	// input框样式
	.custom-input {
		padding: 0 5rpx !important;
		font-size: 29rpx;
		flex: 1;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: flex-end;
		width: 100rpx;
	}

	.edit-device-name-input-error {
		color: red;
		font-size: 22rpx;
		margin-top: 10rpx
	}

	.dayTrue,
	.dayFalse,
	.daySelect,
	.dayDisabled {
		padding: 7rpx 10rpx;
		border-radius: 6rpx
	}

	.dayTrue {
		background: #3d9dcd;
		color: #fff;
		border: 1px solid transparent;
	}

	.dayFalse {
		background: #e0e0e0;
		color: #000;
		border: 1px solid transparent;
	}

	.dayFalse.daySelect,
	.dayTrue.daySelect {
		background: #fff;
		color: #3d9dcd;
		border: 1px solid #3d9dcd;
	}

	.dayDisabled {
		background: #e0e0e0;
		color: #999;
		cursor: not-allowed;
		border: 1px solid transparent;
	}

	.dayDisabled.daySelect {
		background: #e0e0e0;
		color: #999;
		border: 1px solid transparent;
	}
</style>